package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.MovementsApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private MovementsApi movementsApi;

    @Reference
    private UserInfoApi userInfoApi;

    //谁访问过我
    public ResponseEntity visitors() {
        //1 从redis中获取上次登录时间
        String timeValue = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUser().getId());

        List<VisitorsVo> visitorsVoList= new ArrayList<>();
        if(timeValue!=null){
            //2 查询访客
            List<Visitors> list=movementsApi.findvisitors(UserHolder.getUser().getId(),Long.parseLong(timeValue));

            if(CollectionUtil.isNotEmpty(list)){

                for (Visitors visitors : list) {
                    //UserInfo
                    UserInfo userInfo = userInfoApi.findUserInfoVo(visitors.getVisitorUserId());
                    //3 封装app需要的数据
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setUserInfo(userInfo);
                    //缘分值
                    visitorsVo.setFateValue(visitors.getScore().longValue());

                    visitorsVoList.add(visitorsVo);
                }
            }
        }
        //4 将本次的登录时间放入redis中
        stringRedisTemplate.opsForValue().set("visitors_user_" + UserHolder.getUser().getId(),System.currentTimeMillis()+"");

        //5 返回
        return ResponseEntity.ok(visitorsVoList);
    }
}
